import input from '../internal/mixins/input';
import container from './container';
import {
  isNotNull
} from '../utils';

export default {
  name: 'co-select-name',
  mixins: [input, container],
  props: {
    title: String,
    type: {
      type: String,
      default: 'picker',
      validator(value) {
        return ['action-sheet', 'popup', 'picker'].indexOf(value) !== -1;
      }
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    selects() {
      const arr = [];
      this.data.forEach(item => {
        if (this.has(item.name)) {
          arr.push(item);
        }
      });
      return arr;
    }
  },
  methods: {
    has(value) {
      if (this.value === value) return true;
      if (this.multiple && this.value && this.value.length > 0 && this.value.indexOf(value) !== -1) return true;
      return false;
    },
    focus(e) {
      this.isFocused = true;
      this.$emit('focus', e);
    },
    blur(e) {
      this.isFocused = false;
      this.$emit('blur', e);
    },
    open() {
      this.visible = true;
      this.isFocused = true;
    },
    close() {
      this.visible = false;
      this.isFocused = false;
      this.search = '';
    },
    createSelect(h) {
      return [
        h('div', {
          staticClass: 'co-select__content'
        }, [
          isNotNull(this.value) ?
          this.$scopedSlots.selection ?
          this.$scopedSlots.selection({
            selects: this.selects
          }) :
          this.selects.map(({
            name
          }) => name).join(',') :
          h('span', {
            staticClass: 'co-select__placeholder'
          }, this.$attrs.placeholder)
        ]),
        h('co-icon-arrow-drop-down', {
          staticClass: 'co-select__icon'
        })
      ];
    },
    createElement(h) {
      return h('input', {
        attrs: {
          type: 'hidden'
        },
        domProps: {
          value: this.value
        }
      });
    },
    changeValue(value) {
      this.$emit('input', value);
      this.close();
    }
  },
  render(h) {
    return this.createInput(h, {
      staticClass: 'co-select',
      on: {
        click: () => this.open()
      }
    }, [
      ...this.createSelect(h),
      this.createElement(h),
      this.createContainer(h)
    ]);
  }
};
